<style scoped>
.wraper {
    padding: 0 30px;
}

.search {
    padding-bottom: 20px;
}

.search span {
    color: #68777c;
    font-weight: bold;
    padding-right: 18px;
}

.search button {
    background-color: #00a8f7;
    color: #fff;
    margin-left: 8px;
}

.top {
    margin-bottom: 20px;
    border-top: 1px dashed #cccccc;
}

.detail {
    border-top: 1px dashed #cccccc;
}

.wraper .headline {
    position: relative;
    font-size: 12px;
    color: #303134;
    font-weight: bold;
    margin: 10px 0;
    line-height: 32px;
    height: 32px;
}

.wraper .add-agent {
    position: absolute;
    top: 0px;
    right: 30px;
    background-color: #348bf2;
    color: #fff;
}

.iconfont {
    font-size: 14px;
}

.red-font {
    color: #ff1f1f;
}

/* 分页 start */

.page {
    margin: 20px 0;
}
.ivu-page {
    padding-bottom: 150px;
} 

/* 分页 end */
.fl{
    float: left;
}
.all{
    float: left;
    margin-left: 70px;
}

</style>

<template>
    <div class="employee-manage">
        <product-title></product-title>
        <div class="wraper">
            <div class="detail">
                <div class="headline">
                    
                    <Button class="add-agent" @click='showAdd(-1)'>新增角色</Button>
                </div>
                <div class="clearfix">
                    <Table border :columns="columns_role" :data="data_role"></Table>
                </div>
            </div>
        </div>
        <Modal v-model="showAddModal" :mask-closable='closeable' width="600" title="添加/编辑角色" @on-ok="add()" :loading="loading">
            <Row>
                <Col span="18" offset="1">
                    <Form :model="role" ref="role" :rules="ruleValidate" :label-width="120">                   
                        <Form-item label="角色名称：" prop="name" required>
                            <Input v-model="role.name" placeholder="请输入角色名称"></Input>
                        </Form-item>               
                    </Form>
                </Col>
            </Row>
        </Modal>
        <Modal v-model="showactionModal" :mask-closable='closeable' width="1000" title="添加/编辑权限" @on-ok="addaction" :loading="loading">
            <Row>
                <Form :model="action" ref="action" :rules="ruleValidate" :label-width="120">    
                    <Col span="18" offset="1">                               
                        <FormItem label="模块：">
                            <CheckboxGroup v-model="action.active">
                                <Checkbox :label="item.id" v-for="item in module" :key="item.id">
                                    <span>{{item.name}}</span>
                                </Checkbox>
                            </CheckboxGroup>
                        </FormItem>
                    </Col>
                    <Col span="4" offset="1">
                        <Button type="primary" @click="moduleAll()">全选</Button>
                        <Button type="ghost" @click="moduleAllRemove()">全不选</Button>
                    </Col>
                    <div v-for="(value,key) in actionlist" :key="key">                    
                        <Col span="18" offset="1"  >
                            <FormItem :label="key+'：'">
                                <CheckboxGroup v-model="action.active">
                                    <Checkbox :label="item.id" v-for="item in value" :key="item.id">
                                        <span>{{item.name}}</span>
                                    </Checkbox>
                                </CheckboxGroup>
                            </FormItem>
                        </Col>
                        <Col span="4" offset="1">
                            <Button type="primary" @click="actionAll(key)">全选</Button>
                            <Button type="ghost" @click="actionAllRemove(key)">全不选</Button>
                        </Col>  
                    </div>             
                </Form>
                
            </Row>
            <div slot="footer">
                <Button type="primary" class="all" @click="allSelect()">全选</Button><Button type="ghost" class="fl" @click="allSelectRemove()">全不选</Button><Button type="primary" @click="addaction()">确定</Button><Button type="ghost" @click="cancel()">取消</Button>
            </div>
        </Modal>
    </div>
</template>

<script>
import productTitle from '../../components/productTitle'
import { getRoleList , saveRole , updateRole , delRole , getAllModule , getAllAction , saveRoleOperation , getRoleOperation } from '../../api/role'
export default {
    data() {
        return {
            cou:-1,
            checkModal:false,
            showactionModal:false,
            closeable: false,
            loading: true,

            role: {
                name: '',
            },
            action: {
                active:[]
            },
            showAddModal: false,

            columns_role: [
                {
                    type: 'index',
                    title:'序号',
                    width: 60,
                    align: 'center'
                },
                {
                    title: '角色名称',
                    key: 'name',
                    align: 'center',
                },
                {
                    title: '操作',
                    key: 'action',
                    width: 200,
                    align: 'center',
                    render: (h, params) => {
                        return h('div', [
                            h('Button', {
                                props: {
                                    type: 'primary',
                                    size: 'small'
                                },
                                style: {
                                    marginRight: '5px'
                                },
                                on: {
                                    click: () => {
                                        this.showAction(params.row.id)
                                    }
                                }
                            }, '设置权限'),
                            h('Button', {
                                props: {
                                    type: 'primary',
                                    size: 'small'
                                },
                                style: {
                                    marginRight: '5px'
                                },
                                on: {
                                    click: () => {
                                        this.showAdd(params.index)
                                    }
                                }
                            }, '编辑'),
                            h('Button', {
                                props: {
                                    type: 'error',
                                    size: 'small'
                                },
                                on: {
                                    click: () => {
                                        this.delConfirm(params.index)
                                    }
                                }
                            }, '删除')
                        ]);
                    }
                },
            ],
            data_role: [

            ],
            ruleValidate: {
                name: [
                    { required: true, message: '角色名称不能为空', trigger: 'blur' }
                ],
            },
            module:[],
            actionlist:{},
            moduleId:[],
            actionId:[]
        }
    },
    components: {
        productTitle
    },
    created() {
        this.getList()
        this.getModule()
        this.getAction()
    },
    methods: {
        mergeArray(arr1, arr2) { 
            for (var i = 0 ; i < arr1.length ; i ++ ){
                 for(var j = 0 ; j < arr2.length ; j ++ ){
                    if (arr1[i] === arr2[j]){
                        arr1.splice(i,1); //利用splice函数删除元素，从第i个位置，截取长度为1的元素
                    }
                 }
             }
            for(var i = 0; i <arr2.length; i++){
                arr1.push(arr2[i]);
            }
             return arr1;
        },
        array_diff(a, b) {  
            for(var i=0;i<b.length;i++){  
                for(var j=0;j<a.length;j++){  
                    if(a[j]==b[i]){  
                        a.splice(j,1);  
                        j=j-1;  
                    }  
                }  
            }   
            return a;  
        },
        allSelect(){
            this.action.active = this.mergeArray(this.action.active,this.moduleId)
            this.action.active = this.mergeArray(this.action.active,this.actionId)
        },
        allSelectRemove(){
            this.action.active = []
        },
        moduleAll() {           
            this.action.active = this.mergeArray(this.action.active,this.moduleId)
            console.log(this.action.active)

        },
        moduleAllRemove(){
            this.action.active = this.array_diff(this.action.active,this.moduleId)
        },
        actionAll(index){
            let _arr = this.actionlist[index]
            let _temparr = []
            for(var i=0;i<_arr.length;i++){
                _temparr.push(_arr[i].id)
            }
            this.action.active = this.mergeArray(this.action.active,_temparr)
            console.log(this.action.active)
        },
        actionAllRemove(index){
            let _arr = this.actionlist[index]
            let _temparr = []
            for(var i=0;i<_arr.length;i++){
                _temparr.push(_arr[i].id)
            }
            this.action.active = this.array_diff(this.action.active,_temparr)
        },
        // 搜索
        search() {
            this.getList();
        },
        // 获取角色列表
        getList() {
            let _params = {
                cate:2
            }
            new Promise((resolve, reject) => {
                getRoleList(_params).then(response => {
                    console.log(response.data);
                    if (response.data.err == 0) {
                        this.data_role = response.data.data;
                    } else {
                        this.$Message.error(response.data.info);
                    }
                    resolve();
                }).catch(error => {
                    reject(error);
                });
            });
        },
        //
        getModule() {
            new Promise((resolve, reject) => {
                getAllModule().then(response => {
                    console.log(response.data);
                    if (response.data.err == 0) {
                        this.module = response.data.data;
                        for(var i = 0;i<this.module.length;i++){
                            this.moduleId.push(this.module[i].id)
                        }
                    } else {
                        this.$Message.error(response.data.info);
                    }
                    resolve();
                }).catch(error => {
                    reject(error);
                });
            });
        },
        getAction(){
            new Promise((resolve, reject) => {
                getAllAction().then(response => {
                    console.log(response.data);
                    if (response.data.err == 0) {
                        this.actionlist = response.data.data;                        
                        for(var key in this.actionlist ){
                            for(var i =0;i<this.actionlist[key].length;i++){
                                this.actionId.push(this.actionlist[key][i].id)
                            }
                        }
                        console.log(this.actionId)
                    } else {
                        this.$Message.error(response.data.info);
                    }
                    resolve();
                }).catch(error => {
                    reject(error);
                });
            });
        },
        add() {
            this.$refs['role'].validate((valid) => {
                if (valid) {
                    this.role.cate =2   
                    if(this.cou == -1){                      
                        new Promise((resolve, reject) => {
                            saveRole(this.role).then(response => {
                                if (response.data.err == 0) {
                                    this.showAddModal = false;
                                    this.loading = true;
                                    this.getList();
                                    this.$Message.success(response.data.info);
                                } else {
                                    this.$Message.error(response.data.info);
                                    setTimeout(() => {
                                        this.loading = false;
                                        this.$nextTick(() => {
                                            this.loading = true;
                                        });
                                    }, 2000);
                                }
                                resolve();
                            }).catch(error => {
                                reject(error);
                            });
                        });
                    }else{
                          
                        new Promise((resolve, reject) => {
                            updateRole(this.role).then(response => {
                                if (response.data.err == 0) {
                                    this.showAddModal = false;
                                    this.loading = true;
                                    this.getList();
                                    this.$Message.success(response.data.info);
                                } else {
                                    this.$Message.error(response.data.info);
                                    setTimeout(() => {
                                        this.loading = false;
                                        this.$nextTick(() => {
                                            this.loading = true;
                                        });
                                    }, 2000);
                                }
                                resolve();
                            }).catch(error => {
                                reject(error);
                            });
                        });
                    }                   
                } else {
                    // 通过loading来阻止modal隐藏，然后手动修改loading来充值确定按钮
                    setTimeout(() => {
                        this.loading = false;
                        this.$nextTick(() => {
                            this.loading = true;
                        });
                    }, 2000);
                }
            })
        },
        
        del(param) {
            new Promise((resolve, reject) => {
                delRole(param).then(response => {
                    
                    if (response.data.err == 0) {
                        this.$Message.success(response.data.info)
                        this.getList();
                    }
                    resolve();
                }).catch(error => {
                    reject(error);
                });
            });
        },
        //添加or编辑代理人，打开modal
        showAdd(index) {
            this.showAddModal = !this.showAddModal;
            if (index != -1) {
                let params = {
                    'id': this.data_role[index].id
                }
                //this.getDetail(params)
                this.role = Object.assign({}, this.data_role[index] )
                this.cou = 1
            } else {
                this.role.name = ""
                this.cou = -1
            }
        },
        //
        showAction(index) {
            this.showactionModal = !this.showactionModal
            this.action.id = index 
            var _param = {
                id:index
            }
            new Promise((resolve, reject) => {
                getRoleOperation(_param).then(response => {
                    console.log(response.data)                   
                    if (response.data.err == 0) {
                        this.action.active = response.data.data
                    }
                    resolve();
                }).catch(error => {
                    reject(error);
                });
            });     
        },
        addaction(){
            new Promise((resolve, reject) => {
                saveRoleOperation(this.action).then(response => {
                    
                    if (response.data.err == 0) {
                        this.showactionModal = false;
                        this.loading = true;
                        this.getList();
                        this.$Message.success(response.data.info);
                        
                    }else{
                        this.$Message.error(response.data.info);
                        setTimeout(() => {
                            this.loading = false;
                            this.$nextTick(() => {
                                this.loading = true;
                            });
                        }, 2000);
                    }
                    resolve();
                }).catch(error => {
                    reject(error);
                });
            });
        },
        // 删除时弹出对话框
        delConfirm(index) {
            this.$Modal.confirm({
                title: '提示',
                content: '是否要删除该角色?',
                onOk: () => {
                    let _params = {
                        'id': this.data_role[index].id
                    }
                    this.del(_params);
                },
            });
        },
        cancel(){
            this.showactionModal = false;
            this.action.active = []
        }
    }
}
</script>
